Currying transforms a function that takes multiple parameters into a chain of functions and each function taking a single parameter.
def function name(argument1, argument2) = operation
Let us consider the function below to add two values .The function takes in 2 parameters:
object test {
def add(x: Int, y: Int) = x + y;
def main(args: Array[String])
{
println(add(10,20));
}
}
Way to declare currying function
Suppose, we have to transform this add function into a Curried function,
that is transforming the function that takes two(multiple) arguments
into a function that takes one(single) argument.
def function name(argument1) = (argument2) => operation
object Demo
{
def add2(a: Int) = (b: Int) => a + b;
def main(args: Array[String])
{
println(add2(20)(19));
}
}
Output:
39
Here, we have define add2 function which takes only one argument a and
we are going to return a second function which will have the value of
add2. The second function will also take an argument let say b and this
function when called in main, takes two parenthesis(add2()()), where the
first parenthesis is of the function add2 and second parenthesis is of
the second function. It will return the addition of two numbers, that is
a+b. Therefore, we have curried the add function, which means we have
transformed the function that takes two arguments into a function that
takes one argument and the function itself returns the result.
object test {
def add(x: Int) (y: Int) = x + y
def main(args: Array[String])
{
println(add(10)(20));
}
}
Currying Function Using Partial Application
object test
{
def add2(a: Int) = (b: Int) => a + b;
def main(args: Array[String])
{
val sum = add2(29);
println(sum(5));
}
}
Currying Function Using Partial Application
We have another way to use this Curried function and that is Partially
Applied function. So, let’s take a simple example and understand. we
have defined a variable sum in the main function
object Demo
{
def add2(a: Int) = (b: Int) => a + b;
def main(args: Array[String])
{
// Partially Applied function.
val sum = add2(29);
println(sum(5));
}
}
Output:
34
Here, only one argument is passed while assigning the function to the
value. The second argument is passed with the value and these arguments
are added and result is printed.
Also, another way(syntax) to write the currying function.
Syntax
def function name(argument1) (argument2) = operation
object Demo
{
def add2(a: Int) (b: Int) = a + b;
def main(args: Array[String])
{
println(add2(29)(5));
}
}
Output:
34
For this syntax, the Partial Application function also changes.
object Demo
{
def add2(a: Int) (b: Int) = a + b;
def main(args: Array[String])
{
val sum=add2(29)_;
println(sum(5));
}
}
No comments:
Post a Comment